package com.house365.core.thirdpart.auth;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.protocol.HTTP;

import android.os.Bundle;

/**
 * @author py
 * @date 2012-11-6
 * @comment
 */
public class URLUtil {
	public static Bundle decodeUrl(String s) {
		Bundle params = new Bundle();
		if (s != null) {
			String array[] = s.split("&");
			for (String parameter : array) {
				
				String v[] = parameter.split("=");
				if(v!= null && v.length==2){
					params.putString(URLDecoder.decode(v[0]),
							URLDecoder.decode(v[1]));
				}
				
			}
		}
		return params;
	}

	public static Bundle parseUrl(String url) {
		// hack to prevent MalformedURLException
		url = url.replace("weiboconnect", "http");
		try {
			URL u = new URL(url);
			Bundle b = decodeUrl(u.getQuery());
			b.putAll(decodeUrl(u.getRef()));
			return b;
		} catch (MalformedURLException e) {
			return new Bundle();
		}
	}
	public static String genrateGetUrl(String url, List<NameValuePair> olist) {

		if (olist != null && olist.size() > 0) {
			return url + "?" + URLEncodedUtils.format(olist, HTTP.UTF_8);
		} else {
			return url;
		}
	}
	
	
	public static Map<String, String> getQueryParams(String url) {
	    try {
	        Map<String, String> params = new HashMap<String, String>();
	        String[] urlParts = url.split("\\?");
	        if (urlParts.length > 1) {
	            String query = urlParts[1];
	            for (String param : query.split("&")) {
	                String[] pair = param.split("=");
	                String key = URLDecoder.decode(pair[0], "UTF-8");
	                String value = "";
	                if (pair.length > 1) {
	                    value = URLDecoder.decode(pair[1], "UTF-8");
	                }
	                params.put(key, value);
	                /*
	                String values = params.get(key);
	                if (values == null) {
	                    //values = new ArrayList<String>();
	                    params.put(key, values);
	                }
	                */
	                //values.add(value);
	            }
	        }
	        return params;
	    } catch (UnsupportedEncodingException ex) {
	        throw new AssertionError(ex);
	    }
	}

}
